﻿#include <QDebug>
#include <QTimer>
#include <QTime>
#include <QColor>
#include <QtMath>
#include <QtGlobal>

#include <algorithm>
#include <vector>
#include <test.h>
#include <src/operatorSQL.h>

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "include/scheduable.h"
#include "include/rm_schedule.h"
#include "include/task.h"
#include "include/core.h"
#include "include/simul.h"
#include "include/control.h"
using namespace std;
#define max 100
#define max_size 256
int lcm;
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    init_GUI();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::init_GUI()
{
    taskID = 1;
    scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(scene);
    ui->graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    ui->btn_stop->hide();

    header_style = "QHeaderView::section{"
                        "background:rgb(120,120,120);"
                        "color:rgb(255,255,255);"
                        "padding: 1px;}";

    ui->Slider_speed->setInvertedAppearance(true);
    ui->Slider_speed->setMinimum(10);
    ui->Slider_speed->setMaximum(200);
    ui->Slider_speed->setValue(100);

    joined_model = new QStandardItemModel();
    wait_model = new QStandardItemModel();
    utilization_model = new QStandardItemModel();
    randomtask_model = new QStandardItemModel();

    joined_model->setColumnCount(10);
    joined_model->setHeaderData(0, Qt::Horizontal, QString::fromLocal8Bit("ID"));
    joined_model->setHeaderData(1, Qt::Horizontal, QString::fromLocal8Bit("Color"));
    joined_model->setHeaderData(2, Qt::Horizontal, "P("+tau+"i)");
    joined_model->setHeaderData(3, Qt::Horizontal, QString::fromLocal8Bit("ui"));
    joined_model->setHeaderData(4, Qt::Horizontal, QString::fromLocal8Bit("Ci"));
    joined_model->setHeaderData(5, Qt::Horizontal, QString::fromLocal8Bit("Ri"));
    joined_model->setHeaderData(6, Qt::Horizontal, QString::fromLocal8Bit("Di"));
    joined_model->setHeaderData(7, Qt::Horizontal, QString::fromLocal8Bit("Ti"));
    joined_model->setHeaderData(8, Qt::Horizontal, QString::fromStdString("Ni,q"));
    joined_model->setHeaderData(9, Qt::Horizontal, QString::fromStdString("Li,q "));
    //joined_model->setHeaderData(11, Qt::Horizontal, QString::fromStdString("共享资源\n占用类型"));
    //joined_model->setHeaderData(12, Qt::Horizontal, QString::fromStdString("共享资源\n访问状态"));

    wait_model->setColumnCount(6);
    wait_model->setHeaderData(0, Qt::Horizontal, QString::fromLocal8Bit("ID"));
    wait_model->setHeaderData(1, Qt::Horizontal, QString::fromLocal8Bit("State"));
    wait_model->setHeaderData(2, Qt::Horizontal, QString::fromLocal8Bit("Ci"));
    wait_model->setHeaderData(3, Qt::Horizontal, QString::fromLocal8Bit("Di"));
    wait_model->setHeaderData(4, Qt::Horizontal, QString::fromLocal8Bit("Ti"));
    wait_model->setHeaderData(5, Qt::Horizontal, QString::fromLocal8Bit("ui"));

    utilization_model->setColumnCount(5);
    utilization_model->setHeaderData(0, Qt::Horizontal, "Pk");
    utilization_model->setHeaderData(1, Qt::Horizontal, QString::fromLocal8Bit("speed\ncoefficient"));
    utilization_model->setHeaderData(2, Qt::Horizontal, QString::fromLocal8Bit("utilization"));
    utilization_model->setHeaderData(3, Qt::Horizontal, QString::fromLocal8Bit("executing"));
    utilization_model->setHeaderData(4, Qt::Horizontal, QString::fromLocal8Bit("ready"));
    //utilization_model->setHeaderData(5, Qt::Horizontal, QString::fromLocal8Bit("Failure"));
    //utilization_model->setHeaderData(6, Qt::Horizontal, QString::fromLocal8Bit("Recovery"));
    //utilization_model->setHeaderData(7, Qt::Horizontal, QString::fromLocal8Bit("Cluster"));

    randomtask_model->setColumnCount(9);
    randomtask_model->setHeaderData(0, Qt::Horizontal, tau+"i");
    randomtask_model->setHeaderData(1, Qt::Horizontal, QString::fromLocal8Bit("Color"));
    randomtask_model->setHeaderData(2, Qt::Horizontal, QString::fromLocal8Bit("arrive\ntime"));
    randomtask_model->setHeaderData(3, Qt::Horizontal, QString::fromLocal8Bit("release\ntime"));
    randomtask_model->setHeaderData(4, Qt::Horizontal, QString::fromLocal8Bit("Ci"));
    randomtask_model->setHeaderData(5, Qt::Horizontal, QString::fromLocal8Bit("Ti"));
    randomtask_model->setHeaderData(6, Qt::Horizontal, QString::fromLocal8Bit("Ri"));
    randomtask_model->setHeaderData(7, Qt::Horizontal, QString::fromLocal8Bit("Di "));
    randomtask_model->setHeaderData(8, Qt::Horizontal, QString::fromLocal8Bit("schedul-\nable"));

    //在QTableView中加入模型
    ui->table_joined->setModel(joined_model);
//    ui->table_wait->setModel(wait_model);
    ui->table_utilizaiton->setModel(utilization_model);
    ui->table_randomtask->setModel(randomtask_model);

    ui->table_joined->setColumnWidth(0,80);
    ui->table_joined->setColumnWidth(1,80);
    ui->table_joined->setShowGrid(true);
    ui->table_joined->setGridStyle(Qt::DotLine);
    ui->table_joined->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->table_joined->horizontalHeader()->setStyleSheet(header_style);
    QHeaderView *header1 = ui->table_joined->verticalHeader();
    header1->setHidden(true);

//    ui->table_wait->setColumnWidth(0,80);
//    ui->table_wait->setColumnWidth(1,110);
//    ui->table_wait->setShowGrid(true);
//    ui->table_wait->setGridStyle(Qt::DotLine);
//    ui->table_wait->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
//    ui->table_wait->horizontalHeader()->setStyleSheet(header_style);
//    header1 = ui->table_wait->verticalHeader();
    header1->setHidden(true);

    ui->table_utilizaiton->setColumnWidth(0,80);
    ui->table_utilizaiton->setColumnWidth(1,200);
    ui->table_utilizaiton->setShowGrid(true);
    ui->table_utilizaiton->setGridStyle(Qt::DotLine);
    ui->table_utilizaiton->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    QFont font = ui->table_utilizaiton->horizontalHeader()->font();
    font.setBold(true);
    ui->table_utilizaiton->horizontalHeader()->setFont(font);
    ui->table_utilizaiton->horizontalHeader()->setStyleSheet(header_style);  //设置首行样式
    header1 = ui->table_utilizaiton->verticalHeader();
    header1->setHidden(true);

    ui->table_randomtask->setColumnWidth(0,80);
    ui->table_randomtask->setColumnWidth(1,80);
    ui->table_randomtask->setShowGrid(true);
    ui->table_randomtask->setGridStyle(Qt::DotLine);
    ui->table_randomtask->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->table_randomtask->horizontalHeader()->setStyleSheet(header_style);
    header1 = ui->table_randomtask->verticalHeader();
    header1->setHidden(true);

    for(int i = 0; i < 11; ++i){
//        for(int j = 0; j < 6; ++j){
//            item = new QStandardItem(QString("+"));
//            item->setTextAlignment(Qt::AlignHCenter);
//            wait_model->setItem(i, j, item);
//        }

        for(int k = 0; k < 10; ++k){
            item = new QStandardItem(QString("+"));
            item->setTextAlignment(Qt::AlignHCenter);
            joined_model->setItem(i, k, item);
        }

        for(int m = 0; m < 5; ++m){
            item = new QStandardItem(QString("-"));
            item->setTextAlignment(Qt::AlignHCenter);
            utilization_model->setItem(i, m, item);
        }
        for(int n = 0; n < 9; ++n){
             item = new QStandardItem(QString("++"));
             item->setTextAlignment(Qt::AlignHCenter);
             randomtask_model->setItem(i, n, item);
         }
    }

    color[0] = QColor(100,185,140);
    color[1] = QColor(40,125,80);
    color[2] = QColor(128,220,221);
    color[3] = QColor(58,150,150);
    color[4] = QColor(225,128,225);
    color[5] = QColor(165,68,165);
    color[6] = QColor(225,190,100);
    color[7] = QColor(165,130,40);
    color[8] = QColor(100,225,100);
    color[9] = QColor(40,165,40);
    color[10] = QColor(128,120,221);
    color[11] = QColor(58,50,150);
    color[12] = QColor(225,198,225);
    color[13] = QColor(165,128,165);
    color[14] = QColor(170,170,0);
    color[15] = QColor(110,110,0);
    color[16] = QColor(151,255,65);
    color[17] = QColor(91,195,5);
    color[18] = QColor(105,105,0);
    color[19] = QColor(85,85,0);
    color[20] = QColor(0,85,127);
    color[21] = QColor(0,25,67);
    color[22] = QColor(85,0,127);
    color[23] = QColor(25,0,67);
    color[24] = QColor(170,170,255);
    color[25] = QColor(110,110,195);
    color[26] = QColor(225,100,100);
    color[27] = QColor(165,40,40);
    color[28] = QColor(0,0,0);

    //在此处扩充颜色
    for(int i = 0; i < 14; ++i){
        brush[i*8].setColor(color[i*2]);
        brush[i*8].setStyle(Qt::SolidPattern);//核上任务（表任务）
        brush[i*8+1].setColor(color[i*2]);
        brush[i*8+1].setStyle(Qt::Dense7Pattern);//核上局部资源
        brush[i*8+2].setColor(color[i*2]);
        brush[i*8+2].setStyle(Qt::CrossPattern);//核上全局资源
        brush[i*8+3].setColor(color[i*2]);
        brush[i*8+3].setStyle(Qt::SolidPattern);//核上资源标志
        brush[i*8+3].setColor(color[i*2]);
        brush[i*8+4].setStyle(Qt::DiagCrossPattern);//硬实时任务
        brush[i*8+4].setColor(color[i*2]);
        brush[i*8+5].setStyle(Qt::BDiagPattern);//软实时任务
        brush[i*8+5].setColor(color[i*2]);
        brush[i*8+6].setStyle(Qt::Dense4Pattern);//准入控制任务(执行）
        brush[i*8+6].setColor(color[i*2]);
        brush[i*8+7].setStyle(Qt::NoBrush);//准入控制任务(不执行）
        brush[i*8+7].setColor(color[i*2]);
    }

    for(int i = 0; i < 14; ++i){
        pen[i*2].setColor(color[i*2]);//核上任务
        pen[i*2].setWidth(2);
        pen[i*2+1].setColor(color[i*2+1]);//核上资源标志
        pen[i*2+1].setWidth(2);
                                      //默认黑色边缘的资源边缘
    }
     pen[99].setWidth(3);
}


void waitSec(int s)
{
//#ifdef WIN32
//        Sleep(1000);
//#else
//        sleep(1);
//#endif

    QTime t;
    t.start();
    while(t.elapsed()<1000*s)
        QCoreApplication::processEvents();
}

//按下init按钮后所做的一部分工作
void MainWindow::testInit()
{



//    operatorSQL *op = new operatorSQL();
//    QSqlQuery* query = op->queryAll();

//    while (query->next()) {
//        qDebug()<<query->value(0).toInt()
//               <<query->value(1).toString()
//              <<query->value(2).toString();
//    }





    ui->btn_reset->setEnabled(false); //init按钮不可以点击了，防止重复初始化
        qDebug()<<"tasknum"<<taskNum<<endl;
        int row=0;
        resource_type_update();           //更新资源是否为全局资源
        for(int temp=0;temp<get_resourcenum();temp++)     //更新天花板
        {
         if(resource[temp].is_global)
             resource[temp].ceiling_prior=get_global_resource_ceiling_priority(resource[temp].resource_type);
         else
            resource[temp].ceiling_prior=get_local_resource_ceiling_priority(resource[temp].resource_type);
        }

        for(int i = 0 ; i < taskNum ; i++)
            for(int k=0;k<max;k++)
                if(k<taskSets[i].num_subsection)
           { Task *task_now = &taskSets[i];
            joined_task.push_back(task_now);
            Core * core_p = &cores[task_now->on_core];
            if(task_now->task_type!=0)
            {
                //ID
                item = new QStandardItem(tau+QString::number(task_now->task_id)+"("+QString::number(k+1)+")");
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 0, item);
                //Color
                item = new QStandardItem();
                item->setBackground(brush[(task_now->task_id)*8+3+task_now->task_type]);
                joined_model->setItem(row, 1, item);
                //Pi
                item = new QStandardItem(QString::number(task_now->on_core));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 2, item);
                //ui
                item = new QStandardItem(QString::number((double)task_now->task_wcet/(double)task_now->task_period,'f',3));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 3, item);
                //Ci
                item = new QStandardItem(QString::number(task_now->task_wcet));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 4, item);
                //Ri
                item = new QStandardItem(QString::number(task_now->task_wcrt));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 5, item);
                //Di
                item = new QStandardItem(QString::number(task_now->task_period));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 6, item);
                //Ti
                item = new QStandardItem(QString::number(task_now->task_period));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 7, item);
                //Ni,q
                item = new QStandardItem(QString::number(task_now->resource_times[1]) );//参数待修改
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 8, item);
                //Li,q
                item = new QStandardItem(QString::number(task_now->resource_duration[0]));//参数待修改
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 9, item);
            row++;
            }
           else if(task_now->task_type==0&&!task_now->isAccessControl)
           {

                //ID
                item = new QStandardItem(tau+QString::number(task_now->task_id)+"("+QString::number(k+1)+")");
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 0, item);
                //Color
                item = new QStandardItem();
                item->setBackground(brush[(task_now->task_id)*8]);
                joined_model->setItem(row, 1, item);
                //Pi
                item = new QStandardItem(QString::number(task_now->partition.part_on_core[k]));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 2, item);
                //Ui
                item = new QStandardItem(QString::number((double)(task_now->partition.part_length[k])/(double)task_now->task_period, 'f', 3));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 3, item);
                //Ci
                item = new QStandardItem(QString::number(task_now->partition.part_length[k]));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 4, item);
                //Ri
                item = new QStandardItem(QString("-"));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 5, item);
                //Di
                item = new QStandardItem(QString::number(task_now->task_period));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 6, item);
                //Ti
                item = new QStandardItem(QString::number(task_now->task_period));
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 7, item);
                //Ni,q
                item = new QStandardItem(QString::number(task_now->resource_times[0]) );//参数待修改
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 8, item);
                //Li,q
                item = new QStandardItem(QString::number(task_now->resource_duration[0]));//参数待修改
                item->setTextAlignment(Qt::AlignHCenter);
                joined_model->setItem(row, 9, item);
//                //共享资源占用类型
//                item = new QStandardItem(QString::number(task_now->resource_type[k]) );//参数待修改
//                item->setTextAlignment(Qt::AlignHCenter);
//                joined_model->setItem(row, 11, item);
//                //共享资源访问状态
//                item = new QStandardItem(QString::number(task_now->resource_isglobal[k]) );//参数待修改
//                item->setTextAlignment(Qt::AlignHCenter);
//                joined_model->setItem(row, 12, item);
                row++;
           }
         }

        //修改前端utilization区域显示信息
        for(int i = 0; i < M; ++i){
            local_core = &cores[i];
            //Core
            if(local_core->core_type==0)
            item = new QStandardItem(QString("cpu%1").arg(local_core->core_id-1));
           else if(local_core->core_type==1)
            item = new QStandardItem(QString("fpga%1").arg(local_core->core_id-1));
            else if(local_core->core_type==2)
            item = new QStandardItem(QString("gpu%1").arg(local_core->core_id-1));
            else if(local_core->core_type==3)
            item = new QStandardItem(QString("dps%1").arg(local_core->core_id-1));
            item->setTextAlignment(Qt::AlignHCenter);
            utilization_model->setItem(i, 0, item);
            //speed coefficient
            item = new QStandardItem(QString::number(local_core->rate, 'f', 3));
            item->setTextAlignment(Qt::AlignHCenter);
            utilization_model->setItem(i, 1, item);
            //utilization
            item = new QStandardItem(QString::number(get_utilization(local_core), 'f', 3));
            item->setTextAlignment(Qt::AlignHCenter);
            utilization_model->setItem(i, 2, item);
            //ready
            if(local_core->ready_queue->task!=NULL){
            item = new QStandardItem(tau+QString::number(local_core->ready_queue->next->task->task_id));
            item->setTextAlignment(Qt::AlignHCenter);
            utilization_model->setItem(i, 4, item);
            }

//            //fail_prob
//            item = new QStandardItem(QString::number(0, 'f', 2));
//            item->setTextAlignment(Qt::AlignHCenter);
//            utilization_model->setItem(i, 5, item);
//            //recovery_time
//            item = new QStandardItem(QString::number(local_core->recovery_time));
//            item->setTextAlignment(Qt::AlignHCenter);
//            utilization_model->setItem(i, 6, item);
//            //owner_cluster
//            item = new QStandardItem(QString::number(0));
//            item->setTextAlignment(Qt::AlignHCenter);
//            utilization_model->setItem(i, 7, item);
        }


}



void MainWindow::drawPeriod()
{
    //画点线
        qDebug()<<"drawPeriod";
    QPen pen_dotline(QColor(0,0,0));
    pen_dotline.setStyle(Qt::DotLine);
    pen_dotline.setWidth(2);
    scene->addLine(72+Time*30, 0, 72+Time*30, M*80, pen_dotline);
}


void MainWindow::drawStart(Task *task,QPen *pen, QBrush *brush)
{
    qDebug()<<"drawStart";
    QGraphicsLineItem *arrival;
    int arrival_x = (Time ) * 30 + 56 + 16;
    int arrival_y = (task->on_core) * 70 + 20;

    arrival = scene->addLine(arrival_x, arrival_y, arrival_x, arrival_y + 40, pen[(task->task_id) * 2]); //起点坐标，终点坐标，画笔

    QGraphicsPolygonItem *arrivalArrow;

    int arrowLength = 4;
    QVector<QPointF> arrival_point;
    arrival_point.append(QPointF(arrival_x - arrowLength, arrival_y));
    arrival_point.append(QPointF(arrival_x + arrowLength, arrival_y));
    arrival_point.append(QPointF(arrival_x , arrival_y - arrowLength *1.73));
    arrivalArrow = scene->addPolygon(arrival_point);

    arrivalArrow->setBrush(brush[(task->task_id ) * 8]);
    arrivalArrow->setPen(pen[(task->task_id ) * 2]);
}


void MainWindow::seg_drawStart(Task task,int part,QPen *pen, QBrush *brush)
{
    qDebug()<<"seg_drawStart";
    QGraphicsLineItem *arrival;
    int arrival_x = (Time ) * 30 + 56 + 16;
    int arrival_y = (task.partition.part_on_core[part]) * 70 + 20;
   // qDebug()<<"draw start task"<<task.task_id<<"on _core"<<task.on_core<<endl;
    arrival = scene->addLine(arrival_x, arrival_y, arrival_x, arrival_y + 40, pen[(task.task_id) * 2]); //起点坐标，终点坐标，画笔

    QGraphicsPolygonItem *arrivalArrow;

    int arrowLength = 4;
    QVector<QPointF> arrival_point;
    arrival_point.append(QPointF(arrival_x - arrowLength, arrival_y));
    arrival_point.append(QPointF(arrival_x + arrowLength, arrival_y));
    arrival_point.append(QPointF(arrival_x , arrival_y - arrowLength *1.73));
    arrivalArrow = scene->addPolygon(arrival_point);

    arrivalArrow->setBrush(brush[(task.task_id ) * 8]);
    arrivalArrow->setPen(pen[(task.task_id ) * 2]);
}


void MainWindow::drawTransfer(Task *task,QPen *pen)
{
    QGraphicsLineItem *arrival;
    int arrival_x = (Time ) * 30 + 56 + 16;
    int arrival_y = (task->temp_core) * 70 + 20;
  //  qDebug()<<"draw start task"<<task->task_id<<"on _core"<<task->on_core<<endl;
    arrival = scene->addLine(arrival_x, arrival_y, arrival_x, arrival_y + 40, pen[(task->task_id) * 2]); //起点坐标，终点坐标，画笔

    QGraphicsPolygonItem *arrivalArrow;

    int arrowLength = 4;
    QVector<QPointF> arrival_point;
    arrival_point.append(QPointF(arrival_x - arrowLength, arrival_y));
    arrival_point.append(QPointF(arrival_x + arrowLength, arrival_y));
    arrival_point.append(QPointF(arrival_x + arrowLength, arrival_y - arrowLength));
    arrival_point.append(QPointF(arrival_x - arrowLength, arrival_y - arrowLength ));
    arrivalArrow = scene->addPolygon(arrival_point);
    arrivalArrow->setPen(pen[(task->task_id ) * 2]);
}

void MainWindow::seg_drawTransfer(Task task,int part,QPen *pen)
{
    QGraphicsLineItem *arrival;
    int arrival_x = (Time ) * 30 + 56 + 16;
    int arrival_y = (task.partition.part_on_core[part]) * 70 + 20;
//  qDebug()<<"draw start task"<<task.task_id<<"on _core"<<task.on_core<<endl;
    arrival = scene->addLine(arrival_x, arrival_y, arrival_x, arrival_y + 40, pen[(task.task_id) * 2]); //起点坐标，终点坐标，画笔

    QGraphicsPolygonItem *arrivalArrow;

    int arrowLength = 4;
    QVector<QPointF> arrival_point;
    arrival_point.append(QPointF(arrival_x - arrowLength, arrival_y));
    arrival_point.append(QPointF(arrival_x + arrowLength, arrival_y));
    arrival_point.append(QPointF(arrival_x + arrowLength, arrival_y - arrowLength));
    arrival_point.append(QPointF(arrival_x - arrowLength, arrival_y - arrowLength ));
    arrivalArrow = scene->addPolygon(arrival_point);
    arrivalArrow->setPen(pen[(task.task_id ) * 2]);
}

void MainWindow::drawExit(Task *task,QPen *pen)
{
    QGraphicsLineItem *exit;
    int exit_x = (Time ) * 30 + 56 + 16;
    int exit_y = (task->on_core ) * 70 + 18;

    exit = scene->addLine(exit_x, exit_y, exit_x, exit_y + 40, pen[(task->task_id) * 2]);

    QGraphicsLineItem *exitIndex;

    int indexLength = 4;
    exitIndex = scene->addLine(exit_x - indexLength, exit_y, exit_x + indexLength, exit_y);
    exitIndex->setPen(pen[(task->task_id ) * 2]);
}

void MainWindow::seg_drawExit(Task task,int part ,QPen *pen)
{
    QGraphicsLineItem *exit;
    int exit_x = (Time ) * 30 + 56 + 16;
  //  qDebug()<<"draw ends: task"<<task.task_id<<"on _core"<<task.on_core<<endl;
    int exit_y = (task.partition.part_on_core[part] ) * 70 + 18;

    exit = scene->addLine(exit_x, exit_y, exit_x, exit_y + 40, pen[(task.task_id) * 2]);

    QGraphicsLineItem *exitIndex;

    int indexLength = 4;
    exitIndex = scene->addLine(exit_x - indexLength, exit_y, exit_x + indexLength, exit_y);
    exitIndex->setPen(pen[(task.task_id ) * 2]);
}

void MainWindow::seg_drawArrival(Task task,QPen *pen)
{
    QGraphicsLineItem *arrival;
    int arrival_x = (Time+1 ) * 30 + 56 + 16;
    int arrival_y = 4 * 70 + 20;
//  qDebug()<<"draw start task"<<task.task_id<<"on _core"<<task.on_core<<endl;
    arrival = scene->addLine(arrival_x, arrival_y, arrival_x, arrival_y + 40, pen[28]); //起点坐标，终点坐标，画笔

    QGraphicsPolygonItem *arrivalArrow;
    int arrowLength = 8;
    QVector<QPointF> arrival_point;
    arrival_point.append(QPointF(arrival_x - arrowLength*0.5, arrival_y));
    arrival_point.append(QPointF(arrival_x + arrowLength*0.5, arrival_y));
    arrival_point.append(QPointF(arrival_x , arrival_y - arrowLength ));
    arrivalArrow = scene->addPolygon(arrival_point);
    arrivalArrow->setPen(pen[28]);
}


void MainWindow::on_btn_next_clicked()
{
   //(int id, int type, int prior, int jitter, int wcet, int period, int ddl, int arrival_time,int on_core,int joined_row)
    int taskNum_pre = taskNum;
    static int taskNum_table = taskNum;
    if(Time==6)
    {

        ++taskNum;
        initMRTSTask(taskID++,2,35,0,37,200,200,Time,get_minU_core()-1,0);
        taskSets[taskNum-1].resource_start[0]=5;
        taskSets[taskNum-1].resource_type[0]=1;
        taskSets[taskNum-1].resource_duration[0]=1;
        taskSets[taskNum-1].resource_on_core[0]=0;
        taskSets[taskNum-1].resource_index=1;
        taskSets[taskNum-1].temp_core=taskSets[taskNum-1].on_core;
        enqueue_wait_for_join(&taskSets[taskNum-1]);
        ++taskNum;
        initMRTSTask(taskID++,2,38,0,33,500,500,Time,get_minU_core()-1,0);
        taskSets[taskNum-1].resource_start[0]=8;
        taskSets[taskNum-1].resource_type[0]=3;
        taskSets[taskNum-1].resource_duration[0]=1;
        taskSets[taskNum-1].resource_on_core[0]=2;
        taskSets[taskNum-1].resource_start[1]=15;
        taskSets[taskNum-1].resource_type[1]=3;
        taskSets[taskNum-1].resource_duration[1]=1;
        taskSets[taskNum-1].resource_on_core[1]=2;
        taskSets[taskNum-1].resource_index=1;
        taskSets[taskNum-1].temp_core=taskSets[taskNum-1].on_core;
        enqueue_wait_for_join(&taskSets[taskNum-1]);
        ++taskNum;
        initMRTSTask(taskID++,2,37,0,45,500,500,Time,get_minU_core()-1,0);
        taskSets[taskNum-1].resource_start[0]=12;
        taskSets[taskNum-1].resource_type[0]=1;
        taskSets[taskNum-1].resource_duration[0]=2;
        taskSets[taskNum-1].resource_on_core[0]=0;
        taskSets[taskNum-1].resource_start[1]=20;
        taskSets[taskNum-1].resource_type[1]=3;
        taskSets[taskNum-1].resource_duration[1]=1;
        taskSets[taskNum-1].resource_on_core[1]=2;
        taskSets[taskNum-1].resource_index=1;
        taskSets[taskNum-1].temp_core=taskSets[taskNum-1].on_core;
        enqueue_wait_for_join(&taskSets[taskNum-1]);
    }

    if(Time==26)
    {
        ++taskNum;
        initMRTSTask(taskID++,2,36,0,40,800,800,Time,get_minU_core()-1,0);
        taskSets[taskNum-1].resource_start[0]=18;
        taskSets[taskNum-1].resource_type[0]=2;
        taskSets[taskNum-1].resource_duration[0]=1;
        taskSets[taskNum-1].resource_on_core[0]=1;
        taskSets[taskNum-1].resource_index=1;
        taskSets[taskNum-1].temp_core=taskSets[taskNum-1].on_core;
        enqueue_wait_for_join(&taskSets[taskNum-1]);
        ++taskNum;
        initMRTSTask(taskID++,2,31,0,18,800,800,Time,get_minU_core()-1,0);
        enqueue_wait_for_join(&taskSets[taskNum-1]);
        ++taskNum;
        initMRTSTask(taskID++,2,32,0,23,320,320,Time,get_minU_core()-1,0);
        taskSets[taskNum-1].resource_start[0]=12;
        taskSets[taskNum-1].resource_type[0]=2;
        taskSets[taskNum-1].resource_duration[0]=1;
        taskSets[taskNum-1].resource_on_core[0]=1;
        taskSets[taskNum-1].resource_index=1;
        taskSets[taskNum-1].temp_core=taskSets[taskNum-1].on_core;
        enqueue_wait_for_join(&taskSets[taskNum-1]);
    }

    if(Time==40)
    {
        ++taskNum;
        initMRTSTask(taskID++,2,34,0,6,800,800,Time,get_minU_core()-1,0);
        enqueue_wait_for_join(&taskSets[taskNum-1]);
        ++taskNum;
        initMRTSTask(taskID++,2,33,0,50,1000,1000,Time,get_minU_core()-1,0);
        taskSets[taskNum-1].resource_start[0]=2;
        taskSets[taskNum-1].resource_type[0]=2;
        taskSets[taskNum-1].resource_duration[0]=5;
        taskSets[taskNum-1].resource_on_core[0]=1;
        taskSets[taskNum-1].resource_start[1]=10;
        taskSets[taskNum-1].resource_type[1]=3;
        taskSets[taskNum-1].resource_duration[1]=5;
        taskSets[taskNum-1].resource_on_core[1]=2;
        taskSets[taskNum-1].resource_start[2]=21;
        taskSets[taskNum-1].resource_type[2]=1;
        taskSets[taskNum-1].resource_duration[2]=5;
        taskSets[taskNum-1].resource_on_core[2]=3;
        taskSets[taskNum-1].resource_start[3]=30;
        taskSets[taskNum-1].resource_type[3]=4;
        taskSets[taskNum-1].resource_duration[3]=5;
        taskSets[taskNum-1].resource_on_core[3]=0;
        taskSets[taskNum-1].resource_index=1;
        taskSets[taskNum-1].temp_core=taskSets[taskNum-1].on_core;
        enqueue_wait_for_join(&taskSets[taskNum-1]);
    }

    for(;taskNum_pre<taskNum;taskNum_pre++){//非表调度任务进入
        static int row = 0;
        seg_drawArrival(taskSets[taskNum_pre],pen);
        //ID
        item = new QStandardItem(tau+QString::number(taskSets[taskNum_pre].task_id));
        item->setTextAlignment(Qt::AlignHCenter);
        randomtask_model->setItem(row, 0, item);
        //Color
        item = new QStandardItem();
        item->setBackground(brush[(taskSets[taskNum_pre].task_id)*8+3+taskSets[taskNum_pre].task_type]);
        randomtask_model->setItem(row, 1, item);
        //arrive time
        item = new QStandardItem(QString::number(taskSets[taskNum_pre].arrival_time));
        item->setTextAlignment(Qt::AlignHCenter);
        randomtask_model->setItem(row, 2, item);
        //release time
        item = new QStandardItem(QString::fromLocal8Bit("TBD"));
        item->setTextAlignment(Qt::AlignHCenter);
        randomtask_model->setItem(row, 3, item);
        //Ci
        item = new QStandardItem(QString::number(taskSets[taskNum_pre].task_wcet));
        item->setTextAlignment(Qt::AlignHCenter);
        randomtask_model->setItem(row, 4, item);
        //Ti
        item = new QStandardItem(QString::number(taskSets[taskNum_pre].task_period));
        item->setTextAlignment(Qt::AlignHCenter);
        randomtask_model->setItem(row, 5, item);
        //Ri
        item = new QStandardItem(QString::number(taskSets[taskNum_pre].task_wcrt));
        item->setTextAlignment(Qt::AlignHCenter);
        randomtask_model->setItem(row, 6, item);
        //Di
        item = new QStandardItem(QString::number(taskSets[taskNum_pre].task_period));
        item->setTextAlignment(Qt::AlignHCenter);
        randomtask_model->setItem(row, 7, item);
        //schedulnable
        item = new QStandardItem("TBD");
        item->setTextAlignment(Qt::AlignHCenter);
        randomtask_model->setItem(row, 8, item);
        row++;
    }

    for(unsigned int i = 0; i < joined_task.size(); ++i){       //非表调度任务到达
        static int row_ready = 0;;
            if(joined_task[i]->ready_time == Time)
            {
                if(joined_task[i]->task_type!=0)
                {
                    taskNew(joined_task[i], &cores[joined_task[i]->on_core]);
                }
            }
        }



        //非表调度任务退出
        for(int i = 0; i < M; ++i){
            if(cores[i].task_scheduled != -1 && cores[i].task_sched_type!=0){
                Task *scheduled = &taskSets[cores[i].task_scheduled-1];
               // if(scheduled->execute_time == qCeil(scheduled->task_wcet / cores[i].rate)){
                if(scheduled->execute_time == scheduled->task_wcet){
                    drawExit(scheduled, pen);
                    Task *temp = taskExit(scheduled, &cores[i]);
                    if(temp != nullptr)
                        drawExit(temp, pen);
                }
            }
        }

        for(int i = 0; i < M; ++i){                                         //释放共享资源
            if(cores[i].task_scheduled != -1 && cores[i].task_sched_type!=0){
                Task *scheduled = &taskSets[cores[i].task_scheduled-1];
                for(int j=0;j<RESOURCE_MAX;j++)
                if(scheduled->execute_time == (int)(scheduled->resource_start[j]+scheduled->resource_duration[j])&&scheduled->task_id>0)
                {
                  drawTransfer(scheduled,pen);
                  task_release_resource(scheduled,&resource[scheduled->resource_type[j]-1],&cores[scheduled->on_core]);
                  scheduled->temp_core=scheduled->on_core;
                  break;
                }
            }
        }

        for(int i = 0; i < M; ++i){                                         //实时任务迁移
                   if(cores[i].task_scheduled != -1 && cores[i].task_sched_type!=0)
                    {
                       Task *scheduled = &taskSets[cores[i].task_scheduled-1];
                    for(int j=0;j<RESOURCE_MAX;j++)
                   if(scheduled->execute_time == (int)scheduled->resource_start[j]&&scheduled->task_id>0){
                       drawTransfer(scheduled,pen);
                       sched_EnqueueLocal(scheduled,&cores[scheduled->resource_on_core[j]]);
                       sched_SetLocalSchedTask(nullptr,&cores[i]);
                       scheduled->temp_core=scheduled->resource_on_core[j];
                       qDebug()<<"任务"<<scheduled->task_id<<"迁移到核"<<scheduled->temp_core;
                       if(scheduled->resource_type[j]!=0){
                          scheduled->resource_index=j;
                          bool is_success=true;
                          if(scheduled->task_type==1&&resource[scheduled->resource_type[j]-1].is_global)
                          {
                            qDebug()<<"任务"<<scheduled->task_id<<"分段"<<j<<"获取全局资源";
                              is_success=HRT_task_try_to_get_global_resource(scheduled,&cores[scheduled->resource_on_core[j]],
                              &cores[scheduled->resource_on_core[j]],&resource[scheduled->resource_type[j]-1]);
                          }
                          else if(scheduled->task_type==2&&resource[scheduled->resource_type[j]-1].is_global)
                          {
                               qDebug()<<"任务"<<scheduled->task_id<<"分段"<<j<<"获取全局资源";
                              is_success=SRT_task_try_to_get_global_resource(scheduled,&cores[scheduled->resource_on_core[j]],
                                      &cores[scheduled->resource_on_core[j]],&resource[scheduled->resource_type[j]-1]);
                          }
                          else if(scheduled->task_type==1&&!resource[scheduled->resource_type[j]-1].is_global)
                          {
                              qDebug()<<"任务"<<scheduled->task_id<<"分段"<<j<<"获取局部资源";
                              is_success=HRT_task_try_to_get_local_resource(scheduled,&cores[scheduled->resource_on_core[j]],
                                      &resource[scheduled->resource_type[j]-1]);
                          }
                          else if(scheduled->task_type==2&&!resource[scheduled->resource_type[j]-1].is_global)
                          {
                              qDebug()<<"任务"<<scheduled->task_id<<"分段"<<j<<"获取局部资源";
                              is_success=SRT_task_try_to_get_local_resource(scheduled,&cores[scheduled->resource_on_core[j]],
                                      &resource[scheduled->resource_type[j]-1]);
                          }
                          if(is_success!=true)
                         {
                           qDebug()<<"任务"<<scheduled->task_id<<"分段"<<j<<"获取局部资源失败";
                           sched_Schedule(&cores[i]);
                         }
                       }
                       }
                   }
                 }

        //记录上一刻每个处理器上执行的任务
        vector<int> sched_prev(M);
        for(int i = 0; i < M; ++i){
         sched_prev[i] = cores[i].task_scheduled;
        }






        for(int j=0;j<max_size;j++)    //表调度任务结束
            {
              if(taskSets[j].task_type==0)
                for(int k=0;k<max;k++)
               {
                if((taskSets[j].partition.part_length[k]!=0)&&(Time%lcm)==taskSets[j].partition.start[k]+taskSets[j].partition.part_length[k])
                  {
                    cores[taskSets[j].partition.part_on_core[k]].table_task_scheduled =-1;
                    cores[taskSets[j].partition.part_on_core[k]].num_segment =-1;
                    cores[taskSets[j].partition.part_on_core[k]].task_sched_type=-1;
                     if(k%taskSets[j].num_subsection==(taskSets[j].num_subsection-1))
                    seg_drawExit(taskSets[j],k, pen);

                   }

               }
            }

            for(int j=0;j<max_size;j++)//表调度任务开始
            {
                if(taskSets[j].task_type==0)
                for(int k=0;k<max;k++)
               {
                if((taskSets[j].partition.part_length[k]!=0)&&(Time%lcm)==taskSets[j].partition.start[k])
                {
                    taskSets[j].execute_time=0;
                    cores[taskSets[j].partition.part_on_core[k]].table_task_scheduled =j+1;
                    cores[taskSets[j].partition.part_on_core[k]].num_segment =k%taskSets[j].num_subsection+1;
                    cores[taskSets[j].partition.part_on_core[k]].task_sched_type=0;
                    if(k%taskSets[j].num_subsection==0)
                       { if(!taskSets[j].isAccessControl)
                    seg_drawStart(taskSets[j], k, pen,brush);}
                    else
                      {if(!taskSets[j].isAccessControl)
                        seg_drawTransfer(taskSets[j],k, pen);}
                }

               }
            }

            for(int i = 0; i < M; ++i){                     //核上没有表调度任务，对每个核进行实时调度
                    if(cores[i].task_sched_type!=0)
                   sched_Schedule(&cores[i]);
                    }


/*
            for(int i = 0; i < M; ++i){                                         //访问共享资源
                if(cores[i].task_scheduled != -1 && cores[i].task_sched_type!=0)
                 {
                    Task *scheduled = &taskSets[cores[i].task_scheduled-1];
                 for(int j=0;j<RESOURCE_MAX;j++)
                if(scheduled->execute_time == (int)scheduled->resource_start[j]){
                    if(scheduled->resource_type[j]!=0){
                       scheduled->resource_index=j;
                       bool is_success=true;
                       if(scheduled->task_type==1&&resource[scheduled->resource_type[j]-1].is_global)
                       {
                         qDebug()<<"任务"<<scheduled->task_id<<"分段"<<j<<"获取全局资源";
                           is_success=HRT_task_try_to_get_global_resource(scheduled,&cores[scheduled->resource_on_core[j]],
                           &cores[scheduled->resource_on_core[j]],&resource[scheduled->resource_type[j]-1]);
                       }
                       else if(scheduled->task_type==2&&resource[scheduled->resource_type[j]-1].is_global)
                       {
                            qDebug()<<"任务"<<scheduled->task_id<<"分段"<<j<<"获取全局资源";
                           is_success=SRT_task_try_to_get_global_resource(scheduled,&cores[scheduled->resource_on_core[j]],
                                   &cores[scheduled->resource_on_core[j]],&resource[scheduled->resource_type[j]-1]);
                       }
                       else if(scheduled->task_type==1&&!resource[scheduled->resource_type[j]-1].is_global)
                       {
                           qDebug()<<"任务"<<scheduled->task_id<<"分段"<<j<<"获取局部资源";
                           is_success=HRT_task_try_to_get_local_resource(scheduled,&cores[scheduled->resource_on_core[j]],
                                   &resource[scheduled->resource_type[j]-1]);
                       }
                       else if(scheduled->task_type==2&&!resource[scheduled->resource_type[j]-1].is_global)
                       {
                           qDebug()<<"任务"<<scheduled->task_id<<"分段"<<j<<"获取局部资源";
                           is_success=SRT_task_try_to_get_local_resource(scheduled,&cores[scheduled->resource_on_core[j]],
                                   &resource[scheduled->resource_type[j]-1]);
                       }
                       if(is_success!=true)
                      {
                        qDebug()<<"任务"<<scheduled->task_id<<"分段"<<j<<"获取局部资源失败";
                        sched_Schedule(&cores[i]);
                      }
                    }
                    }
                }
              }

*/
            //非表调度任务如果下一刻将要执行的任务和上一刻执行的不一样，就要绘制任务开始执行的标志
            for(int i = 0; i < M; ++i){
                    if(cores[i].task_scheduled != -1 && cores[i].task_scheduled != sched_prev[i]&&cores[i].task_sched_type!=0){
                        Task *scheduled = &taskSets[cores[i].task_scheduled-1];
                        if(!scheduled->isRestart){
                            drawStart(scheduled, pen, brush);
                            scheduled->isRestart = true;
                        }
                    }
            }

                for(int i = 0; i < M; ++i){                            //任务执行中
                    int row = cores[i].core_id-1;
                        if(cores[i].task_sched_type!=0&&cores[i].task_scheduled!=-1)
                        {
                            Task *current = &taskSets[cores[i].task_scheduled-1];
                            current->execute_time++;
                            rectangle = scene->addRect(Time * 30 + 56 + 16, (cores[i].core_id-1) * 70 + 30, 30, 30);
                            if(current->execute_time == 1&&current->task_id >=1){
                                QString text = "T";
                                text += (QString::number(current->task_id));
                                QGraphicsTextItem *table_driven_text = scene->addText(text, QFont("Consolas", 6.5, -1, true));
                                table_driven_text->setPos(Time * 30 + 56 + 14, (cores[i].core_id-1) * 70 + 35);
                                current->first_release = false;
                            }
                            rectangle->setBrush(brush[(current->task_id)*8+3+current->task_type]);
                            rectangle->setPen(pen[(current->task_id)*2]);
                           }
                        else if(cores[i].task_sched_type==0&&cores[i].table_task_scheduled!=0)
                        {
                            Task *current = &taskSets[cores[i].table_task_scheduled-1];
                            current->execute_time++;
                            rectangle = scene->addRect(Time * 30 + 56 + 16, (cores[i].core_id-1) * 70 + 30, 30, 30);
                            if(current->execute_time == 1&&current->task_id >=1){
                                QString text = "T";
                                text += (QString::number(current->task_id)+"("+QString::number(cores[i].num_segment)+")");
                                QGraphicsTextItem *table_driven_text = scene->addText(text, QFont("Consolas", 6.5, -1, true));
                                table_driven_text->setPos(Time * 30 + 56 + 14, (cores[i].core_id-1) * 70 + 35);
                                current->first_release = false;}

                            if(current->isAccessControl)                              //表调度任务决定是否入队
                            {
                              //  show_waitqueue();
                                if(wait_for_join->next!=wait_for_join)
                                {
                                     for(ready_queue_node *temp = wait_for_join->next; temp != wait_for_join; temp = temp->next)

                                     {
                                         if(schedulable_analyse(taskSets,temp->task))
                                         //if(true)
                                         {
                                             temp->task->ready_time=1+Time+temp->task->task_jitter;//时间为什么+1
                                             joined_task.push_back(temp->task);
                                             for(int i=0;i<taskNum-taskNum_table;i++){
                                                if(ui->table_randomtask->model()->index(i,8).data().toString() == "TBD"){
                                                    item = new QStandardItem("yes");
                                                    item->setTextAlignment(Qt::AlignHCenter);
                                                    randomtask_model->setItem(i, 8, item);
                                                    item = new QStandardItem(QString::number(temp->task->ready_time-1));
                                                    item->setTextAlignment(Qt::AlignHCenter);
                                                    randomtask_model->setItem(i, 3, item);
                                                }
                                            }
                                         }
                                         else
                                         {
                                             for(int i=0;i<taskNum-taskNum_table;i++){
                                                if(ui->table_randomtask->model()->index(i,8).data().toString() == "TBD"){
                                                    item = new QStandardItem("no");
                                                    item->setTextAlignment(Qt::AlignHCenter);
                                                    randomtask_model->setItem(i, 8, item);
                                                    item = new QStandardItem("denied");
                                                    item->setTextAlignment(Qt::AlignHCenter);
                                                    randomtask_model->setItem(i, 3, item);
                                                }
                                            }
                                         }
                                         dequeue_wait_for_join(temp->task);
                                       //  show_waitqueue();
                                         resource_bind(temp->task);
                                         resource_type_update();           //更新资源是否为全局资源
                                         for(int temp=0;temp<get_resourcenum();temp++)
                                         {
                                          if(resource[temp].is_global)
                                             resource[temp].ceiling_prior= get_global_resource_ceiling_priority(resource[temp].resource_type);
                                          else
                                            resource[temp].ceiling_prior=  get_local_resource_ceiling_priority(resource[temp].resource_type);
                                         }
                                     }
                                     testInit(); //更新加入的任务
                                     rectangle->setBrush(brush[(current->task_id)*8+6]); //brush[i*4].setStyle(Qt::SolidPattern)
                                     rectangle->setPen(pen[(current->task_id)*2]);
                                }
                                else
                                {
                                    rectangle->setBrush(brush[(current->task_id)*8+7]); //brush[i*4].setStyle(Qt::SolidPattern)
                                    rectangle->setPen(pen[(current->task_id)*2+1]);
                                }
                            }
                            else
                            {
                             rectangle->setBrush(brush[(current->task_id)*8]);
                             rectangle->setPen(pen[(current->task_id)*2]);
                            }
                           }

                    //在Runtime Information区域展示的信息
                    QString item_text = tau + QString::number(taskSets[cores[i].task_scheduled-1].task_id);
                    item = new QStandardItem(item_text);
                item->setTextAlignment(Qt::AlignHCenter);
                utilization_model->setItem(row, 3, item);
                }
          Time++;
        /*if(Time%lcm==1&&Time!=1)
           drawPeriod();
             */

    }


/*Init按钮:
 *根据设定的处理器信息与表调度任务信息初始化
 *图形界面，并对系统中的数据结果进行初始化。
 *(testInit()中实现）
 **/
void MainWindow::on_btn_reset_clicked()
{
    //初始化计时器
    Time = 0;

    int text_y = 30;
    for(int i = 0; i < M; ++i){
        QString name;
        if(cores[i].core_type==0)
        name = "cpu";
        if(cores[i].core_type==1)
        name = "fpga";
        if(cores[i].core_type==2)
        name = "gpu";
        if(cores[i].core_type==3)
        name = "dsp";
        name += QString::number(i);
        text = scene->addText(name);
        text->setPos(45, text_y);
        text->setFont(QFont("Consolas", 10, -1, true));
        text_y += 70;
    }
    QPen pen_coordinate(Qt::black);
    //虚线
    QPen pen_dashLien(QColor(20, 210, 210));
    pen_dashLien.setStyle(Qt::DashLine);
    coordinate = scene->addLine(70 + 31, 0, 70 + 31, M*70 + 10, pen_coordinate);
    coordinate = scene->addLine(70 + 31, 10, 1032 + 31 + 5100, 10, pen_dashLien);
    coordinate = scene->addLine(70 + 31, M*70 + 10, 1060 + 31 + 5100, M*70 + 10, pen_coordinate);

    text = scene->addText((QString::number(0)));
    text->setFont(QFont("Consolas", 10, -1, true));
    text->setPos(62 + 31, M*70 + 28);

    int index = 1;
    for(int i = 101 + 31; i < 1060 + 5120; i += 30){
        //0 1 2 3的虚线
        coordinate = scene->addLine(i, 10, i, M*70 + 10, pen_dashLien);
        QGraphicsItem *index_line;
        index_line = scene->addLine(i, M*70 + 10, i, M*70 + 25, pen_coordinate);
//        index_line = scene->addLine(0, 10, i, M*70 + 25, pen_coordinate);
        text = scene->addText((QString::number(index)));
        text->setFont(QFont("Consolas", 10, -1, true));
        text->setPos(i - 10, M*70 + 28);
        index += 1;
    }
    QVector<QPointF> point_sets;

    point_sets.append(QPointF(1057.5 + 31 + 5100, M*70 + 4));
    point_sets.append(QPointF(1060 + 31 + 5100, M*70 + 10));
    point_sets.append(QPointF(1057.5 + 31 + 5100, M*70 + 16));
    point_sets.append(QPointF(1073 + 31 + 5100, M*70 + 10));

    QGraphicsPolygonItem *tritangle = scene->addPolygon(QPolygonF(point_sets));
    tritangle->setBrush(Qt::black);

    //图例
    int index_h = 40;

    //任务到达图例
    int arrival_x = 155;
    int arrival_y = (M + 1) * 70;
    QGraphicsLineItem *arrival = scene->addLine(arrival_x, arrival_y, arrival_x, arrival_y + index_h, QPen(QBrush(Qt::black), 2));

    QGraphicsPolygonItem *arrivalArrow;
    int arrowLength = 4;
    QVector<QPointF> arrival_point;
    arrival_point.append(QPointF(arrival_x - arrowLength, arrival_y));
    arrival_point.append(QPointF(arrival_x + arrowLength, arrival_y));
    arrival_point.append((QPointF(arrival_x, arrival_y - arrowLength * 1.73)));
    arrivalArrow = scene->addPolygon(arrival_point);
    arrivalArrow->setPen(QPen(QBrush(Qt::black), 2));
    arrivalArrow->setBrush(Qt::black);

    QGraphicsTextItem *arrivalText = scene->addText("任务", QFont("Consolas"));
    arrivalText->setPos(arrival_x + 15, arrival_y - 5);
    arrivalText = scene->addText("释放", QFont("Consolas"));
    arrivalText->setPos(arrival_x + 15, arrival_y + index_h/3);

    //任务终止图例
    QGraphicsLineItem *exit;
    int exit_x = arrival_x + 150;
    int exit_y = (M+1) * 70;
    exit = scene->addLine(exit_x, exit_y, exit_x, exit_y + 40, QPen(Qt::black, 2));

    QGraphicsLineItem *exitIndex;
    int indexLength = 4;
    exitIndex = scene->addLine(exit_x-indexLength, exit_y, exit_x + indexLength, exit_y);
    exitIndex->setPen(QPen(Qt::black, 2));

    QGraphicsTextItem *exitText = scene->addText("任务", QFont("Consolas"));
    exitText->setPos(exit_x + 15, exit_y - 5);
    exitText = scene->addText("结束", QFont("Consolas"));
    exitText->setPos(exit_x + 15, exit_y + index_h/3);


    //周期图例
    int period_x = arrival_x + 300;
    int period_y = (M+1) * 70;
    QPen pen_dotline(QColor(0,0,0));
    pen_dotline.setStyle(Qt::DotLine);
    pen_dotline.setWidth(2);
    scene->addLine(period_x, period_y, period_x, period_y+40, pen_dotline);

    QGraphicsTextItem *periodText = scene->addText("超周期", QFont("Consolas"));
    periodText->setPos(period_x + 15, period_y - 5);

    //任务迁移图例

    int trans_x = arrival_x +450;
    int trans_y = (M+1) * 70;
    QGraphicsLineItem *trans = scene->addLine(trans_x, trans_y, trans_x,trans_y + index_h, QPen(QBrush(Qt::black), 2));
    QGraphicsPolygonItem *trans_sqr;
    int transLength = 4;
    QVector<QPointF> trans_point;
   trans_point.append(QPointF(trans_x - transLength, trans_y));
    trans_point.append(QPointF(trans_x + transLength, trans_y));
   trans_point.append(QPointF(trans_x + transLength, trans_y - transLength ));
   trans_point.append(QPointF(trans_x - transLength, trans_y - transLength ));
    trans_sqr= scene->addPolygon(trans_point);
    trans_sqr->setPen(QPen(QBrush(Qt::black), 2));

    QGraphicsTextItem *transText = scene->addText("任务", QFont("Consolas"));
   transText->setPos(trans_x + 15, trans_y - 5);
    transText = scene->addText("迁移", QFont("Consolas"));
    transText->setPos(trans_x + 15, trans_y + index_h/3);

    qDebug()<<"before init"<<endl;

    testInit();
}




void MainWindow::on_btn_start_clicked()
{
    ui->btn_start->hide();
    ui->btn_stop->show();
    stop_flag = true;

    while(stop_flag){
        QEventLoop loop;
        QTimer::singleShot(10*simulation_speed, this, SLOT(on_btn_next_clicked()));
        QTimer::singleShot(10*simulation_speed, &loop, SLOT(quit()));
        loop.exec();
    }
}

void MainWindow::on_btn_stop_clicked()
{
    stop_flag = false;
    qDebug()<<"stop"<<endl;
    ui->btn_stop->hide();
    ui->btn_start->show();
}

void MainWindow::on_Slider_speed_valueChanged(int value)
{
    simulation_speed = value;
    qDebug()<<"speed:"<<simulation_speed<<endl;
}





void MainWindow::on_action1cpu_1dsp_triggered()
{
    ui->action1cpu_1dsp->setCheckable(false);
    ui->action1cpu_1dsp->setChecked(true);
    M = 4;
    cluster_num = 1;
    cluster_core_num = 4;

    core_utilization = init_core_list_head();

    initLocalCore(1, 1.5, 0);
    initLocalCore(2, 1.5, 0);
    initLocalCore(3, 1.5 ,3);
    initLocalCore(4, 1.5 ,3);

}



void MainWindow::on_heter_taskset_triggered()
{
    lcm=1;
    wait_for_join = init_task_list_head();       //T1
    struct subsection temp;
    memset(temp.part_length,0,sizeof(temp.part_length));
    memset(temp.part_on_core,0xFF,sizeof(temp.part_length));
    memset(temp.start,0,sizeof(temp.part_length));
    temp.part_length[0]=5;
    temp.part_length[1]=3;
    temp.part_length[2]=10;
    temp.part_length[3]=6;
    temp.part_length[4]=5;
    temp.part_on_core[0]=0;
    temp.part_on_core[1]=0;
    temp.part_on_core[2]=0;
    temp.part_on_core[3]=0;
    temp.part_on_core[4]=0;
    temp.start[0]=1;
    temp.start[1]=20;
    temp.start[2]=60;
    temp.start[3]=90;
    temp.start[4]=100;
    ++taskNum;
    initTask(taskID++,temp,100,5,0);



    memset(temp.part_length,0,sizeof(temp.part_length));
    memset(temp.part_on_core,0xFF,sizeof(temp.part_length));
    memset(temp.start,0,sizeof(temp.part_length));

   temp.part_length[0]=2;
   temp.part_length[1]=3;
   temp.part_length[2]=1;
   temp.part_length[3]=5;
   temp.part_length[4]=22;
    temp.part_on_core[0]=1;
    temp.part_on_core[1]=1;
    temp.part_on_core[2]=1;
     temp.part_on_core[3]=1;
     temp.part_on_core[4]=1;
    temp.start[0]=1;
    temp.start[1]=5;
    temp.start[2]=10;
    temp.start[3]=20;
    temp.start[4]=30;
    //T2
    ++taskNum;
    initTask(taskID++,temp,100,5,0);


    memset(temp.part_length,0,sizeof(temp.part_length));
    memset(temp.part_on_core,0xFF,sizeof(temp.part_length));
    memset(temp.start,0,sizeof(temp.part_length));
    temp.part_length[0]=2;
    temp.part_length[1]=2;
    temp.part_length[2]=5;
    temp.part_length[3]=1;
    temp.part_length[4]=9;
    temp.part_on_core[0]=2;
    temp.part_on_core[1]=2;
    temp.part_on_core[2]=2;
    temp.part_on_core[3]=2;
    temp.part_on_core[4]=2;
    temp.start[0]=20;
    temp.start[1]=30;
    temp.start[2]=50;
    temp.start[3]=60;
    temp.start[4]=70;
    //T3
    ++taskNum;
    initTask(taskID++,temp,100,5,0);


    memset(temp.part_length,0,sizeof(temp.part_length));
    memset(temp.part_on_core,0xFF,sizeof(temp.part_length));
    memset(temp.start,0,sizeof(temp.part_length));
    temp.part_length[0]=1;
    temp.part_length[1]=2;
    temp.part_length[2]=1;
    temp.part_length[3]=3;
    temp.part_length[4]=1;
    temp.part_length[0]=2;
    temp.part_on_core[0]=3;
    temp.part_on_core[1]=3;
    temp.part_on_core[2]=3;
    temp.part_on_core[3]=3;
    temp.part_on_core[4]=3;
    temp.start[0]=2;
    temp.start[1]=5;
    temp.start[2]=8;
    temp.start[3]=33;
    temp.start[4]=40;
    //T4
    ++taskNum;
    initTask(taskID++,temp,100,5,0);

    for(int i=0; i<max_size; i++) {
            if(taskSets[i].task_period!=0&&taskSets[i].task_type==0)
            lcm=lcm*taskSets[i].task_period/(__gcd(lcm,taskSets[i].task_period)); //求最小公倍数
        }
    qDebug()<<"lcm is"<<lcm<<endl;

   for(int i=0;i<M;i++)                                     //形成核上表调度的表
   {
       int table_num=0;
       for(int j=0;j<taskNum;j++)
        for(int k=0;k<max;k++)
          {  if(taskSets[j].partition.start[k]!=0&&(int)taskSets[j].partition.part_on_core[k]==i)
            {
             cores[i].table[table_num].start=taskSets[j].partition.start[k];
             cores[i].table[table_num].end=taskSets[j].partition.start[k]+taskSets[j].partition.part_length[k];
             cores[i].table[table_num].task_id=j;
             cores[i].table[table_num].num_seg=k;
             table_num++;
            }
         }
         cores[i].table_length=table_num;
         queue_core_table(&cores[i]);
    }



   int min_window=10000;                                     //找准入控制分配核
   int min_core=0;
   for(int i=0;i<M;i++)
   {
      int max_window=0;
      int temp_window=0;
      for(int j=0;j<cores[i].table_length;j++)
      {
          temp_window+= cores[i].table[j].end-cores[i].table[j].start;
          if(cores[i].table[j].end!=cores[i].table[j+1].start)
             if(max_window<temp_window)
               {
                 max_window=temp_window;
                 temp_window=0;
               }

      }
      if(min_window>max_window)
         {
           min_window=max_window;
           min_core=i;
         }
   }


   int num_accesscontrol=0;
   memset(temp.part_length,0,sizeof(temp.part_length));
   memset(temp.part_on_core,0xFF,sizeof(temp.part_length));
   memset(temp.start,0,sizeof(temp.part_length));

   qDebug()<<"表长度"<<cores[min_core].table_length;

   for(int k=0;k<cores[min_core].table_length;k++)                                                     //插入准入控制任务
   {
      if(cores[min_core].table[k].end!=cores[min_core].table[k+1].start)
      {
          temp.part_length[num_accesscontrol]=1;
          temp.part_on_core[num_accesscontrol]=min_core;
          temp.start[num_accesscontrol]=cores[min_core].table[k].end;
          qDebug()<<"add end"<<temp.start[num_accesscontrol]<<"num_accesscontrol"<<endl;
          num_accesscontrol++;

      }
      if(k!=0&&cores[min_core].table[k].start!=cores[min_core].table[k-1].end)
      {
          temp.part_length[num_accesscontrol]=1;
          temp.part_on_core[num_accesscontrol]=min_core;
          temp.start[num_accesscontrol]=cores[min_core].table[k].start-1;
         qDebug()<<"add start"<<temp.start[num_accesscontrol]<<num_accesscontrol<<"num_accesscontrol"<<endl;
          num_accesscontrol++;

      }
      for(int x=0;x<cores[min_core].table[k+1].start-cores[min_core].table[k].end;x+=(3+min_window))
      {
          temp.part_length[num_accesscontrol]=1;
          temp.part_on_core[num_accesscontrol]=min_core;
          temp.start[num_accesscontrol]=cores[min_core].table[k].end+x;
           qDebug()<<"add mid"<<temp.start[num_accesscontrol]<<num_accesscontrol<<"num_accesscontrol"<<endl;
          num_accesscontrol++;
      }
   }



    for(int k=0;k<lcm-cores[min_core].table[cores[min_core].table_length-1].start;k+=(3+min_window))
    {
        temp.part_length[num_accesscontrol]=1;
        temp.part_on_core[num_accesscontrol]=min_core;
        temp.start[num_accesscontrol]=cores[min_core].table[cores[min_core].table_length-1].end+k;
        num_accesscontrol++;
        qDebug()<<"add more"<<temp.start[num_accesscontrol-1]<<endl;
    }
    ++taskNum;
    initAccessControl(taskID++,temp,lcm,num_accesscontrol,0);
    for(int i=0;i<100;i++)
    {
        if(taskSets[4].partition.part_length[i]!=0)
            qDebug()<<taskSets[4].partition.start[i];
    }
  /*  ++taskNum;
    initMRTSTask(taskID++,1,12,0,8,40,40,2,1,0);  //硬实时全局
    taskSets[5].resource_start[0]=3;
    taskSets[5].resource_type[0]=1;
    taskSets[5].resource_duration[0]=2;
    taskSets[5].resource_on_core[0]=0;
    taskSets[5].resource_index=1;
    taskSets[5].temp_core=taskSets[6].on_core;
    ++taskNum;
    initMRTSTask(taskID++,2,25,0,16,40,40,3,1,0);  //软实时全局
    taskSets[6].resource_start[0]=2;
    taskSets[6].resource_type[0]=1;
    taskSets[6].resource_duration[0]=4;
    taskSets[6].resource_on_core[0]=0;
    taskSets[6].resource_index=1;
    taskSets[6].temp_core=taskSets[7].on_core;
    ++taskNum;
    initMRTSTask(taskID++,2,20,0,8,50,50,0,0,0);  //real time task        //软实时局部资源
    taskSets[7].resource_start[0]=4;
    taskSets[7].resource_type[0]=2;
    taskSets[7].resource_duration[0]=2;
    taskSets[7].resource_on_core[0]=0;
    taskSets[7].resource_index=1;
    taskSets[7].temp_core=taskSets[8].on_core;
    ++taskNum;
    initMRTSTask(taskID++,1,15,0,8,50,50,0,1,0);  //real time task         //硬实时局部资源
    taskSets[8].resource_start[0]=4;
    taskSets[8].resource_type[0]=3;
    taskSets[8].resource_duration[0]=2;
    taskSets[8].resource_on_core[0]=1;
    taskSets[8].resource_index=1;
    taskSets[8].temp_core=taskSets[9].on_core;
    ++taskNum;
    initMRTSTask(taskID++,1,10,0,8,50,50,18,1,0);        //硬实时局部资源
    taskSets[9].resource_start[0]=4;
    taskSets[9].resource_type[0]=3;
    taskSets[9].resource_duration[0]=2;
    taskSets[9].resource_on_core[0]=1;
    taskSets[9].resource_index=1;
    taskSets[9].temp_core=taskSets[10].on_core;*/
    resource_init(1);
    resource_init(2);
    resource_init(3);
    resource_init(4);
}


void MainWindow::on_heter_multicore_triggered()
{
    mode=3;
}


void MainWindow::on_actionstart_triggered()
{

}




